package cn.fntop.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fn
 * @description
 * @date 2023/8/4 11:18
 */
public class OpenApiContext {
    private static final ThreadLocal<Map<Class<?>, OpenApiServiceSubject>> CONTEXT = new ThreadLocal<>();
    public static <T extends OpenApiServiceSubject> T get(Class<T> clazz) {
        Map<Class<?>, ?> subjects = CONTEXT.get();
        if (subjects == null) {
            return null;
        }
        T apiService = (T) subjects.get(clazz);
        if (apiService == null) {
            return null;
        }
        return apiService;
    }

    public static void set(Class<? extends OpenApiServiceSubject> clazz, OpenApiServiceSubject subject) {
        Map<Class<?>, OpenApiServiceSubject> subjects = new ConcurrentHashMap<>();
        if (CONTEXT.get() == null) {
            CONTEXT.set(subjects);
        }
        Map<Class<?>, OpenApiServiceSubject> subjectMap = CONTEXT.get();
        subjectMap.putIfAbsent(clazz, subject);
        CONTEXT.set(subjectMap);

    }
}
